package cn.jiangjiesheng.bootstrap.gateway.commons;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;

import java.util.Map;

/**
 * Created by dev@jiangjiesheng.cn on 2022/9/13  <br/>
 *
 * @author dev@jiangjiesheng.cn
 */
@Slf4j
@Component
@Order(-2)
public class GlobalErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request,
                                                  ErrorAttributeOptions options) {
        Map<String, Object> map = super.getErrorAttributes(
                request, options);
        map.put("status", HttpStatus.BAD_REQUEST);
        final Throwable error = getError(request);
        log.error("{}", error);
        if (error.getStackTrace().length>0){
            map.put("message", String.format("%s:%d, Error:%s", error.getStackTrace()[0].getFileName(),
                    error.getStackTrace()[0].getLineNumber(), error.getMessage()));
        }
        return map;
    }
}
